import { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Space,
  Card,
  Tag,
  Input,
  Select,
  Modal,
  message,
  Dropdown,
  Image,
  Row,
  Col,
  Statistic,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  MoreOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  FileImageOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import useDishesStore from '../../store/dishes/useDishesStore';
import DishForm from './DishForm';
import dayjs from 'dayjs';

const { Search } = Input;
const { Option } = Select;

const DishesList = () => {
  const [modalVisible, setModalVisible] = useState(false);
  const [categoryDetailModalVisible, setCategoryDetailModalVisible] = useState(false);
  const [editingDish, setEditingDish] = useState(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [searchText, setSearchText] = useState('');
  
  const {
    dishes,
    loading,
    filters,
    getDishes,
    deleteDish,
    toggleDishStatus,
  } = useDishesStore();

  useEffect(() => {
    getDishes(filters);
  }, []);

  const statusConfig = {
    online: { color: 'success', icon: <CheckCircleOutlined />, text: '已上线' },
    offline: { color: 'error', icon: <CloseCircleOutlined />, text: '已下线' }
  };

  const categories = [...new Set(dishes.map(d => d.category))];
  
  const statisticsByCategory = categories.reduce((acc, category) => {
    acc[category] = dishes.filter(d => d.category === category && d.status === 'online').length;
    return acc;
  }, {});

  const statistics = {
    total: dishes.length,
    online: dishes.filter(d => d.status === 'online').length,
    offline: dishes.filter(d => d.status === 'offline').length,
    byCategory: statisticsByCategory
  };

  const columns = [
    {
      title: '菜品名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      render: (name) => (
        <span style={{ fontWeight: 500, fontSize: 14 }}>{name}</span>
      ),
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 120,
      render: (category) => (
        <Tag color="blue">{category}</Tag>
      ),
    },
    {
      title: 'Slug',
      dataIndex: 'slug',
      key: 'slug',
      width: 180,
      render: (slug) => (
        <Tag color="cyan" style={{ fontSize: 12 }}>{slug}</Tag>
      ),
    },
    {
      title: '图片',
      dataIndex: 'images',
      key: 'images',
      width: 200,
      render: (images) => (
        <>
          {images && images.length > 0 ? (
            <Image.PreviewGroup>
              <Space size={8}>
                {images.slice(0, 3).map((url, index) => (
                  <Image
                    key={index}
                    width={50}
                    height={50}
                    src={url}
                    style={{ objectFit: 'cover', borderRadius: 4, cursor: 'pointer' }}
                  />
                ))}
                {images.length > 3 && (
                  <div style={{ 
                    width: 50, 
                    height: 50, 
                    background: '#f0f0f0', 
                    borderRadius: 4,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontSize: 12,
                    color: '#666',
                    fontWeight: 500
                  }}>
                    +{images.length - 3}
                  </div>
                )}
              </Space>
            </Image.PreviewGroup>
          ) : (
            <div style={{ 
              width: 50, 
              height: 50, 
              background: '#f0f0f0', 
              borderRadius: 4,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}>
              <FileImageOutlined style={{ color: '#999' }} />
            </div>
          )}
        </>
      ),
    },
    {
      title: '规格价格',
      key: 'variants',
      width: 250,
      render: (_, record) => (
        <Space direction="vertical" size={4}>
          {record.variants.map((variant, index) => (
            <div key={index} style={{ fontSize: 12 }}>
              <Tag color="geekblue">{variant.size}</Tag>
              <span style={{ fontWeight: 500 }}>¥{(variant.price * variant.discount / 100).toFixed(2)}</span>
              {variant.discount < 100 && (
                <>
                  <span style={{ textDecoration: 'line-through', color: '#999', marginLeft: 8 }}>
                    ¥{variant.price}
                  </span>
                  <Tag color="red" style={{ marginLeft: 8 }}>{variant.discount}%</Tag>
                </>
              )}
            </div>
          ))}
        </Space>
      ),
    },
    {
      title: '上线时间',
      dataIndex: 'launchTime',
      key: 'launchTime',
      width: 180,
      render: (time) => dayjs(time).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => {
        const config = statusConfig[status];
        return (
          <Tag color={config.color} icon={config.icon}>
            {config.text}
          </Tag>
        );
      },
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 180,
      render: (time) => dayjs(time).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 120,
      render: (_, record) => {
        const items = [
          {
            key: 'edit',
            label: '编辑',
            icon: <EditOutlined />,
            onClick: () => handleEdit(record),
          },
          {
            type: 'divider',
          },
        ];

        if (record.status === 'offline') {
          items.push({
            key: 'online',
            label: '上线',
            icon: <CheckCircleOutlined />,
            onClick: () => handleStatusChange(record.id, 'online'),
          });
        } else {
          items.push({
            key: 'offline',
            label: '下线',
            icon: <CloseCircleOutlined />,
            onClick: () => handleStatusChange(record.id, 'offline'),
          });
        }

        items.push(
          { type: 'divider' },
          {
            key: 'delete',
            label: '删除',
            icon: <DeleteOutlined />,
            danger: true,
            onClick: () => handleDelete(record),
          }
        );

        return (
          <Dropdown
            menu={{ items }}
            trigger={['click']}
          >
            <Button type="text" icon={<MoreOutlined />} />
          </Dropdown>
        );
      },
    },
  ];

  const handleEdit = (record) => {
    setEditingDish(record);
    setModalVisible(true);
  };

  const handleDelete = (record) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除菜品"${record.name}"吗？此操作不可恢复。`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          await deleteDish(record.id);
          message.success('删除成功');
        } catch {
          message.error('删除失败');
        }
      },
    });
  };

  const handleStatusChange = async (id, status) => {
    try {
      await toggleDishStatus(id, status);
      message.success('状态更新成功');
    } catch {
      message.error('状态更新失败');
    }
  };

  const handleBatchDelete = () => {
    Modal.confirm({
      title: '批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个菜品吗？`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          for (const id of selectedRowKeys) {
            await deleteDish(id);
          }
          message.success('批量删除成功');
          setSelectedRowKeys([]);
        } catch {
          message.error('批量删除失败');
        }
      },
    });
  };

  const handleStatusFilter = (status) => {
    getDishes({ status });
  };

  const handleSearch = (value) => {
    setSearchText(value);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
  };

  const filteredDishes = searchText
    ? dishes.filter(dish =>
        dish.name.toLowerCase().includes(searchText.toLowerCase()) ||
        dish.category.toLowerCase().includes(searchText.toLowerCase())
      )
    : dishes;

  return (
    <div className="p-6">
      <Row gutter={16} className="mb-6">
        <Col span={6}>
          <Card>
            <Statistic
              title="全部菜品"
              value={statistics.total}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已上线"
              value={statistics.online}
              valueStyle={{ color: '#3f8600' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已下线"
              value={statistics.offline}
              valueStyle={{ color: '#cf1322' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title={
                <Space>
                  <span>分类总数</span>
                  <Button
                    type="link"
                    size="small"
                    icon={<EyeOutlined />}
                    onClick={() => setCategoryDetailModalVisible(true)}
                    style={{ padding: 0 }}
                  >
                    查看详情
                  </Button>
                </Space>
              }
              value={Object.keys(statistics.byCategory).length}
            />
          </Card>
        </Col>
      </Row>

      <Card>
        <div style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Space size={12}>
            <Select
              value={filters.status}
              style={{ width: 120 }}
              onChange={handleStatusFilter}
            >
              <Option value="all">全部状态</Option>
              <Option value="online">已上线</Option>
              <Option value="offline">已下线</Option>
            </Select>
            <Search
              placeholder="搜索菜品名称或分类"
              allowClear
              onSearch={handleSearch}
              style={{ width: 250 }}
            />
            {selectedRowKeys.length > 0 && (
              <Button danger onClick={handleBatchDelete}>
                批量删除 ({selectedRowKeys.length})
              </Button>
            )}
          </Space>

          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setEditingDish(null);
              setModalVisible(true);
            }}
          >
            创建菜品
          </Button>
        </div>

        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={filteredDishes}
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条`,
            defaultPageSize: 10,
          }}
          scroll={{ x: 1200 }}
        />
      </Card>

      <Modal
        title={editingDish ? '编辑菜品' : '创建菜品'}
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setEditingDish(null);
        }}
        footer={null}
        width={800}
        destroyOnClose
      >
        <DishForm
          dish={editingDish}
          onSuccess={() => {
            setModalVisible(false);
            setEditingDish(null);
            getDishes(filters);
          }}
          onCancel={() => {
            setModalVisible(false);
            setEditingDish(null);
          }}
        />
      </Modal>

      <Modal
        title="分类详情"
        open={categoryDetailModalVisible}
        onCancel={() => setCategoryDetailModalVisible(false)}
        footer={null}
        width={600}
      >
        <Space direction="vertical" size={12} style={{ width: '100%' }}>
          {Object.entries(statistics.byCategory).map(([category, count]) => (
            <div 
              key={category} 
              style={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center',
                padding: '12px 16px',
                background: '#f5f5f5',
                borderRadius: '8px',
                transition: 'all 0.2s'
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = '#e6f4ff'}
              onMouseLeave={(e) => e.currentTarget.style.background = '#f5f5f5'}
            >
              <Tag color="processing" style={{ margin: 0 }}>{category}</Tag>
              <span style={{ fontWeight: 600, fontSize: 18, color: '#1890ff' }}>{count}</span>
            </div>
          ))}
        </Space>
      </Modal>
    </div>
  );
};

export default DishesList;